import React, { PureComponent, Fragment } from 'react';
import { connect } from 'dva';
import {
  Row,
  Col,
  Card,
  Form,
  Input,
  Button,
  Modal,
  Badge,
  Divider,
  Icon
} from 'antd';
import TableList from '@/components/TableList';
import PageHeaderWrapper from '@/components/PageHeaderWrapper';
import styles from '../search.less';
const FormItem = Form.Item;
const { TextArea } = Input;
const getValue = obj =>
  Object.keys(obj)
    .map(id => obj[id])
    .join(',');
const statusMap = ['success', 'error'];
const status = ['正常', '冻结'];
const formLayout = {
  labelCol: { span: 6 },
  wrapperCol: { span: 18 },
};

@connect(({ authorize, loading }) => ({
  authorize,
  loading: loading.models.authorize,
}))
@Form.create()
class authorize extends PureComponent {
  state = {
    modalVisible: false,
    selectedRows: [],
    formValues: {},
  };

  columns = [
    {
      title: '终端编号',
      dataIndex: 'terminalCode',
    },
    {
      title: 'MAC地址',
      dataIndex: 'macAddr',
    },

    {
      title: '注册时间',
      dataIndex: 'createTime',
    },

    {
      title: '当前版本',
      dataIndex: 'terminalVersion',
    },

    {
      title: '使用人',
      dataIndex: 'userList',
      width: "20%",
      render: (text) => (
        <div className={styles.colRemark} title={text}>
          {text}
        </div>
      )
    },
    {
      title: '状态',
      dataIndex: 'terminalState',
      render(val) {
        return <Badge status={statusMap[val]} text={status[val]} />;
      },
    },
    {
      title: '操作',
      render: (text, record) => (
        <Fragment>
          <a onClick={() => this.handleDetailModalVisible(true, record)}>详情</a>
          <Divider type="vertical" />
          <a onClick={() => this.handleEditStatus(record,1)}>冻结</a>
          <Divider type="vertical" />
          <a onClick={() => this.handleEditStatus(record,0)}>解冻</a>
        </Fragment>
      ),
    },
  ];

  componentDidMount() {
    this.pageList()
  }

  handleEditStatus(record,type) {
    const todo = type===0?'解冻':'冻结';
    Modal.confirm({
      title: todo,
      content: '您确定要'+todo+'以下数据吗？',
      okText: '确认',
      cancelText: '取消',
      onOk: () => this.todoEditStatus(record,type),
    });
  }

  todoEditStatus(record,type) {
    const { dispatch } = this.props;
    const values = {
      id: record.id,
      terminalState: type,
    };
    dispatch({
      type: 'authorize/update',
      payload: values,
      callback: (res) => {
        if(res.result == "ok") {
          Modal.success({title: res.msg});
          this.pageList();
        }else {
          Modal.error({title: '操作失败',content: res.msg});
        }
      }
    });
  }

  // 分页查询列表
  pageList(data,pageSize=10,pageNum=0) {
    const { dispatch } = this.props;
    const values = {
      macAddr: data && data.macAddr || '',
      terminalVersion: data && data.terminalVersion || '',
      pageSize: pageSize,
      pageNum: pageNum,
    };
    dispatch({
      type: 'authorize/queryList',
      payload: values,
    });
  }

  handleStandardTableChange = (pagination, filtersArg, sorter) => {
    const {formValues} = this.state;
    // 分页请求
    this.pageList(formValues,pagination.pageSize,pagination.current-1);
  };

  //查询
  handleSearch = e => {
    e.preventDefault();
    const { dispatch, form } = this.props;
    form.validateFields((err, fieldsValue) => {
      if (err) return;
      const values = {
        ...fieldsValue,
        updatedAt: fieldsValue.updatedAt && fieldsValue.updatedAt.valueOf(),
      };
      this.setState({
        formValues: values,
      });
      this.pageList(values)
    });
  };

  handleDetailModalVisible = (flag,text) => {
    this.setState({
      detailModalVisible: !!flag,
      text
    });
  };

  renderSimpleForm() {
    const {
      form: {getFieldDecorator},
    } = this.props;
    return (
      <Form onSubmit={this.handleSearch} layout="inline">
        <Row gutter={{md: 8, lg: 24, xl: 48}}>
          <Col md={8} sm={24}>
            <FormItem label="MAC地址">
              {getFieldDecorator('macAddr')(<Input placeholder=""/>)}
            </FormItem>
          </Col>

          <Col md={8} sm={24}>
            <FormItem label="当前版本">
              {getFieldDecorator('terminalVersion')(<Input placeholder=""/>)}
            </FormItem>
          </Col>

          <Col md={8} sm={24}>
            <span className={styles.submitButtons}>
              <Button type="primary" htmlType="submit">
                查询
              </Button>
            </span>
          </Col>
        </Row>
      </Form>
    );
  }

  renderForm() {
    return this.renderSimpleForm();
  }

  render() {
    const {
      authorize: { data },
      loading,
    } = this.props;
    const { selectedRows, modalVisible, updateModalVisible, editFormValues,detailModalVisible, text } = this.state;

    const parentMethods = {
      handleAdd: this.handleAdd,
      handleModalVisible: this.handleModalVisible,
    };
    const updateMethods = {
      handleUpdateModalVisible: this.handleUpdateModalVisible,
      handleUpdate: this.handleUpdate,
    };
    const detailsMethods = {
      handleDetailModalVisible: this.handleDetailModalVisible,
    };
    return (
      <PageHeaderWrapper title="终端授权">
      <Card bordered={false}>
        <div className={styles.tableList}>
          <div className={styles.tableListForm}>{this.renderForm()}</div>

          <TableList
            selectedRows={selectedRows}
            loading={loading}
            data={data}
            columns={this.columns}
            onSelectRow={this.handleSelectRows}
            onChange={this.handleStandardTableChange.bind(this)}
            rowKey={record => record.id}
          />
        </div>
        {detailModalVisible?<Details {...detailsMethods} detailModalVisible={detailModalVisible} text={text} />:null}

      </Card>
      </PageHeaderWrapper>
    );
  }
}

//查看详情弹窗
class Details extends PureComponent {
  constructor(props) {
    super(props);
  }

  render() {
    const { detailModalVisible, handleDetailModalVisible,text } = this.props;
    return (
      <Modal
        destroyOnClose
        width={800}
        title="查看详情"
        visible={detailModalVisible}
        onCancel={() => handleDetailModalVisible(false)}
        footer={[
          <Button key="back" type="primary" onClick={() => handleDetailModalVisible()}>返回</Button>
        ]}
        className={styles.viewMore}
      >
        <Row>
          <Col md={12}>
            <FormItem id="clientCode" {...formLayout} label="终端编号">
            {text.terminalCode}
            </FormItem>
          </Col>

          {/*<Col md={12}>
            <FormItem id="ipAddr" {...formLayout} label="IP地址">
              {text.macAddr}
            </FormItem>
          </Col>*/}

          <Col md={12}>
          <FormItem id="macAddr" {...formLayout} label="MAC地址">
            {text.macAddr}
          </FormItem>
          </Col>

          <Col md={12}>
          <FormItem id="localVersion" {...formLayout} label="当前版本">
           {text.terminalVersion}
          </FormItem>
          </Col>

          <Col md={12}>
        <FormItem id="registTime" {...formLayout} label="注册时间">
          {text.createTime}
        </FormItem>
          </Col>

          <Col md={12}>
            <FormItem id="userName" {...formLayout} label="使用人">
              {text.userList}
            </FormItem>
          </Col>

          {/*<Col md={12}>
            <FormItem id="authority" {...formLayout} label="权限">
              {text.rightIds}
            </FormItem>
          </Col>*/}

          <Col md={12}>
            <FormItem id="status" {...formLayout} label="状态">
              {text.terminalState==0?'正常':'冻结'}
            </FormItem>
          </Col>
        </Row>
      </Modal>
    );
  }
}

export default authorize;
